package com.training.service;

import com.training.entity.OfflinePractice;
import com.training.mapper.OfflinePracticeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class OfflinePracticeService {

    private final OfflinePracticeMapper practiceMapper;

    @Autowired
    public OfflinePracticeService(OfflinePracticeMapper practiceMapper) {
        this.practiceMapper = practiceMapper;
    }

    /**
     * 创建线下实践
     */
    @Transactional
    public boolean createPractice(OfflinePractice practice) {
        // 约束校验
        if (practice.getTitle() == null || practice.getTitle().trim().isEmpty() ||
                practice.getContent() == null || practice.getContent().trim().isEmpty() ||
                practice.getPracticeTime() == null) {
            throw new IllegalArgumentException("实践标题、内容和时间均不能为空。");
        }
        if (practice.getPracticeTime().isBefore(LocalDateTime.now())) {
            throw new IllegalArgumentException("实践时间必须是未来的时间。");
        }

        // 设置初始状态
        practice.setStatus("进行中");
        return practiceMapper.insertPractice(practice) > 0;
    }

    /**
     * 根据教师ID和关键词搜索实践
     */
    public List<OfflinePractice> searchPracticesByTeacher(Long teacherId, String keyword) {
        return practiceMapper.findByTeacherIdAndKeyword(teacherId, keyword);
    }

    /**
     * 根据ID获取实践详情
     */
    public OfflinePractice getPracticeById(Long id) {
        return practiceMapper.findById(id);
    }


    /**
     * 取消线下实践
     */
    @Transactional
    public boolean cancelPractice(Long practiceId, Long teacherId) {
        OfflinePractice practice = practiceMapper.findById(practiceId);
        if (practice == null || !practice.getTeacherId().equals(teacherId)) {
            // 实践不存在或不属于该教师
            return false;
        }
        return practiceMapper.updateStatus(practiceId, teacherId, "已取消") > 0;
    }

    /**
     * 结束线下实践
     */
    @Transactional
    public boolean closePractice(Long practiceId, Long teacherId) {
        OfflinePractice practice = practiceMapper.findById(practiceId);
        if (practice == null || !practice.getTeacherId().equals(teacherId)) {
            return false;
        }
        return practiceMapper.updateStatus(practiceId, teacherId, "已结束") > 0;
    }
    // 在 OfflinePracticeService.java 文件的末尾添加以下方法
    public List<OfflinePractice> getPracticesByCourseId(Long courseId) {
        return practiceMapper.findByCourseId(courseId);
    }
}